import json
import time
import logging
import datetime
import pandas as pd

import QUANTAXIS as QA
from QUANTAXIS.QAARP import QA_Risk
from QIFIAccount.QIFIAccount.QARealtimeStockSim import QIFI_StockSIM_Account
from QAStrategy.QAStrategy.classic_strategy.grid_strategy import GridTrade


def main():
    # account
    username = 'admin'
    password = 'admin'

    # strategy
    print('start execute strategy')
    today = datetime.date.today()
    last_week = datetime.date.today() + datetime.timedelta(days=-30)
    last_year = datetime.date.today() + datetime.timedelta(days=-365)

    start = last_week.strftime('%Y-%m-%d')
    end = today.strftime('%Y-%m-%d')
    end = QA.QA_util_get_pre_trade_date(end, n=1)
    start = '2020-07-20'
    end = '2021-01-07'
    # start = '2020-04-12'
    # end = '2020-06-12'
    weight_pos = [1.0, 0.9, 0.7, 0.5, 0.3, 0.1, 0.0]
    weight_distance = [-3, -2, -1, 2, 4, 6]

    strategy = GridTrade(username='grid_backtest_index_min', password='123456', code='510300',
                         market=QA.MARKET_TYPE.INDEX_CN, start=start, end=end, show_trade=True,
                         min_trade_money=3000,
                         frequence=QA.FREQUENCE.THIRTY_MIN, strategy_id=username, init_cash=1e5,
                         deadband=0.1, dynamic=True, N=30, err='atr', atr_ratio=2,
                         weight_pos=weight_pos, weight_distance=weight_distance)
    strategy.run_backtest()
    strategy.plot_grid()
    risk = QA_Risk(strategy.acc)
    # print(risk.risk_message)
    # s = pd.Series(risk.risk_message)
    # s['start'] = start
    # print(s)
    df = pd.DataFrame.from_dict(risk.risk_message, orient='index', columns=['values']).T
    # df.to_csv('bt_result.csv')
    risk.plot_assets_curve().show()

if __name__ == "__main__":
    try:
        from QUANTAXIS_RealtimeCollector.QARealtimeCollector.utils.logconf import update_log_file_config
        logfile = 'stock.backtest.log'
        logging.config.dictConfig(update_log_file_config(logfile))
    except Exception as e:
        print(e.__str__())
    # main_muti()
    main()